package com.yao.dubboconsumer.rpc;

import com.yao.dubboconsumer.client.NettyClientConsumer;
import com.yao.dubboconsumer.discovery.ServiceDiscovery;
import com.yao.dubboconsumer.discovery.impl.ServiceDiscoveryImpl;
import com.yao.dubboconsumer.loadbalance.LoadBalance;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 消费者端 服务代理类
 *
 * @author Henry Yao
 * @since 2021/5/3
 */
public class RpcProxy {
    public static <T> T creat(Class<T> serviceClass) {
        return (T) Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                return rpcInvoke(method, objects, serviceClass);
            }
        });

    }

    /**
     * 执行代理方法
     *
     * @param method
     * @param objects
     * @return
     */
    private static Object rpcInvoke(Method method, Object[] objects, Class serviceClass) throws Exception {
        // 服务发现
        ServiceDiscovery discovery = new ServiceDiscoveryImpl();
        String provider = discovery.discovery(serviceClass.getSimpleName(), LoadBalance.Type.RANDOM);
        // 远程调用
        NettyClientConsumer consumer = new NettyClientConsumer();
        return consumer.doRpc(method, objects, provider,serviceClass.getSimpleName());
    }
}
